package chapter04

import java.io.{BufferedReader, FileReader}

/**
 * @author: 余辉
 * @blog: https://blog.csdn.net/silentwolfyh
 * descriptions:
 * date: 2024 - 09 - 02 11:02 上午
 */
class FileRdd(val path: String) extends Rdd {
  override val iter = compute()
  override var dep: List[Rdd] = Nil

  override def compute(): Iterator[String] = {
    new FileIterator(path)
  }

  override def map(f: String => String): MapRdd = {
    new MapRdd(iter => iter.map(f), List(this))
  }

  override def foreach(f: String => Unit): Unit = iter.foreach(f)

  class FileIterator(val s: String) extends Iterator[String] {
    private val br = new BufferedReader(new FileReader(s))
    private var line: String = _
    private var flag:Boolean = false

    override def hasNext: Boolean = {
      line = br.readLine()
      if(line != null) flag = true else flag=false
      flag
    }

    override def next(): String = {
      line
    }
  }
}